# $Id: config.py 9227e81e919a 2012/08/27 15:49:57 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: 9227e81e919a $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-08-27 15:49:57Z $"

import ConfigParser
import os

from exception import LexerError
import stdlib

class Section(object):
   def __init__(self, Name, Items = []):
      self._name = None
      self._items = []

      if Name:
         self._name = Name

      if Items:
         self._items = Items

   def __str__(self):
      return stdlib.my_str(self._name)

   def __getitem__(self, Key):
      retval = getattr(self, Key)
      if retval is None:
         raise KeyError("invalid key '%s'" %Key)

      return retval

   def __getattr__(self, value):
      retval = None
      for ix in self._items:
         if len(ix) >= 2 and ix[0] == value:
            retval = ix[1]
            break

      return retval

   def __contains__(self, name):
      retval = False
      for ix in self._items:
         if len(ix) >= 2 and ix[0] == name:
            retval = True
            break

      return retval


class Lexer(object):
   def __init__(self, ConfigFile):
      self._file = None
      self._fh = ConfigParser.SafeConfigParser()

      if os.path.exists(ConfigFile):
         self._file = ConfigFile

      if self._file:
         self._fh.read(self._file)
      else:
         raise LexerError("Non existent or invalid config file!")

   def __len__(self):
      return len(self._fh.sections())

   def __str__(self):
      return stdlib.my_str(self._file)

   def __contains__(self, Name):
      retval = False
      if isinstance(Name, str) and Name in self._fh.sections():
         retval = True

      return retval

   def __getattr__(self, name):
      retval = None
      if name in self:
         retval = Section(name, self._fh.items(name))

      return retval
